from functools import wraps
from flask import jsonify, request
from flask_jwt_extended import get_jwt_identity
from app.models import User, Permission

def admin_required(f):
    """管理员权限装饰器"""
    @wraps(f)
    def decorated_function(*args, **kwargs):
        current_user_id = int(get_jwt_identity())
        user = User.query.get(current_user_id)
        
        if not user:
            return jsonify({'message': '用户不存在'}), 401
        
        if not user.is_active:
            return jsonify({'message': '账户已被禁用'}), 401
        
        if not user.is_superuser:
            return jsonify({'message': '权限不足'}), 403
        
        return f(*args, **kwargs)
    return decorated_function

def permission_required(permission_code):
    """权限验证装饰器"""
    def decorator(f):
        @wraps(f)
        def decorated_function(*args, **kwargs):
            current_user_id = int(get_jwt_identity())
            user = User.query.get(current_user_id)
            
            if not user:
                return jsonify({'message': '用户不存在'}), 401
            
            if not user.is_active:
                return jsonify({'message': '账户已被禁用'}), 401
            
            # 超级管理员拥有所有权限
            if user.is_superuser:
                return f(*args, **kwargs)
            
            # 检查用户是否有指定权限
            user_permissions = set()
            for role in user.roles:
                if role.is_active:
                    for permission in role.permissions:
                        if permission.is_active:
                            user_permissions.add(permission.code)
            
            if permission_code not in user_permissions:
                return jsonify({'message': '权限不足'}), 403
            
            return f(*args, **kwargs)
        return decorated_function
    return decorator

def role_required(role_code):
    """角色验证装饰器"""
    def decorator(f):
        @wraps(f)
        def decorated_function(*args, **kwargs):
            current_user_id = int(get_jwt_identity())
            user = User.query.get(current_user_id)
            
            if not user:
                return jsonify({'message': '用户不存在'}), 401
            
            if not user.is_active:
                return jsonify({'message': '账户已被禁用'}), 401
            
            # 超级管理员拥有所有角色
            if user.is_superuser:
                return f(*args, **kwargs)
            
            # 检查用户是否有指定角色
            user_roles = {role.code for role in user.roles if role.is_active}
            
            if role_code not in user_roles:
                return jsonify({'message': '权限不足'}), 403
            
            return f(*args, **kwargs)
        return decorated_function
    return decorator 